/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package 解析.node.node;

import 解析.node.others.TreeInfo;
import 解析.Matcher;

/**
 *
 * @author yanxi
 */
public class LazyLoop extends Loop {

    public LazyLoop(int countIndex, int beginIndex) {
        super(countIndex, beginIndex);
    }

    @Override
    public boolean match(Matcher matcher, int i, CharSequence seq) {
        // Check for zero length group
        if (i > matcher.locals[beginIndex]) {
            int count = matcher.locals[countIndex];
            if (count < cmin) {
                matcher.locals[countIndex] = count + 1;
                //boolean result = body.match(matcher, i, seq);
                boolean result = getBody().match(matcher, i, seq);
                // If match failed we must backtrack, so
                // the loop count should NOT be incremented
                if (!result) {
                    matcher.locals[countIndex] = count;
                }
                return result;
            }
            if (next.match(matcher, i, seq)) {
                return true;
            }
            if (count < cmax) {
                matcher.locals[countIndex] = count + 1;
                boolean result = getBody().match(matcher, i, seq);
                // If match failed we must backtrack, so
                // the loop count should NOT be incremented
                if (!result) {
                    matcher.locals[countIndex] = count;
                }
                return result;
            }
            return false;
        }
        return next.match(matcher, i, seq);
    }

    boolean matchInit(Matcher matcher, int i, CharSequence seq) {
        int save = matcher.locals[countIndex];
        boolean ret = false;
        if (0 < cmin) {
            matcher.locals[countIndex] = 1;
            ret = getBody().match(matcher, i, seq);
        } else if (next.match(matcher, i, seq)) {
            ret = true;
        } else if (0 < cmax) {
            matcher.locals[countIndex] = 1;
            ret = getBody().match(matcher, i, seq);
        }
        matcher.locals[countIndex] = save;
        return ret;
    }

    @Override
    public boolean study(TreeInfo info) {
        info.maxValid = false;
        info.deterministic = false;
        return false;
    }
    
    @Override
    public String toString(){ 
        return super.toString()+"?";
    }
}
